package com.dingding.dubbo.framework.protocol.http;


import com.dingding.dubbo.framework.Invocation;
import com.dingding.dubbo.framework.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @program: spring-learning
 * @description:
 * @author: liugongding
 * @create: 2022-01-13 15:56
 **/
public class HttpServerHandler {

    public void handler(HttpServletRequest request, HttpServletResponse response) {
        try {
            Invocation invocation = (Invocation) new ObjectInputStream(request.getInputStream()).readObject();
            String interfaceName = invocation.getInterfaceName();
            String methodName = invocation.getMethodName();
            Class implClass = LocalRegister.get(interfaceName);
            Method method = implClass.getMethod(methodName, invocation.getParamTypes());
            Object invoke = method.invoke(implClass.newInstance(), invocation.getParams());
            IOUtils.write((String)invoke, response.getOutputStream());
        } catch (IOException | ClassNotFoundException | NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }
}
